package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;
    @Resource
    private IFollowService followService;
    @Override
    public Result queryById(Long id) {
        Blog blog = this.getById(id);
        if (blog == null)return Result.fail("笔记不存在");
        findUser(blog);
        isLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryHotById(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            findUser(blog);
            //查询用户对该笔记是否点过赞
            isLiked(blog);
        });
        return Result.ok(records);
    }
    @Override
    public Result liskBlog(Long id) {
        //redis的key
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //用户id
        Long userId = UserHolder.getUser().getId();
        //判断是否点个赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //没点过
        if (score == null) {
            //笔记点赞数加1
            boolean isSuccess = this.update().setSql("liked = liked + 1").eq("id", id).update();
            //在redis中记录点赞者
            if (isSuccess){
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else {
            //点赞过
            //笔记点赞数减1
            boolean isSuccess = this.update().setSql("liked = liked - 1").eq("id", id).update();
            //在redis中删除点赞者
            if (isSuccess){
                stringRedisTemplate.opsForZSet().remove (key,userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result likedList(Long id) {
        //redis的key
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //从redis中获取点赞列表top5
        Set<String> users = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (users == null||users.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = users.stream().map(Long::valueOf).collect(Collectors.toList());
        //如查询到的id顺序为112 4 1,mysql不会按这个顺序搜索，需要在sql后面添加 ORDER BY field(id,112,4,1)
        String idsStr = StrUtil.join(",", ids);
        List<UserDTO> userDTOS = userService.query().in("id",ids)
                .last(" ORDER BY field(id,"+idsStr+")")
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail("笔记上传失败");
        }
        //把博文发送给关注者
        //查询所有关注者 select * from tb_follow where follow_user_id = ?
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        for (Follow follow : follows) {
            //关注者id
            Long userId = follow.getUserId();
            //推送博文 ZADD key value score
            String key = RedisConstants.FEED_KEY+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long maxTime, Integer offset) {
        //根据时间戳和偏移量从redis中获取用户的推送列表
        String key = RedisConstants.FEED_KEY + UserHolder.getUser().getId();
        //ZREVRANGEBYSCORE key max min WITHSCORES LIMIT OFFSET NUMB
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
                .opsForZSet().reverseRangeByScoreWithScores(key, 0, maxTime, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //获取此时最小的时间戳
        long minTime = 0;
        //最小时间戳的重复次数
        Integer minNUM = 1;
        //获取笔记id列表
        List<Long> ids = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String blogId = typedTuple.getValue();
            ids.add(Long.valueOf(blogId));
            long blogTime = typedTuple.getScore().longValue();
            if(blogTime == minTime){
                minNUM++;
            }else {
                minTime = blogTime;
                minNUM = 1;
            }
        }
        //获取笔记
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            findUser(blog);
            isLiked(blog);
        }
        //封装
        ScrollResult res = new ScrollResult();
        res.setList(blogs);
        res.setOffset(minNUM);
        res.setMinTime(minTime);
        return Result.ok(res);
    }

    private void isLiked(Blog blog){
        //用户id
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return;
        }
        Long userId = user.getId();

        //redis的key
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        //判断是否点个赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    private void findUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
